package com.starsea.book.ui.newpage.activity

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdLoadType
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.lxj.xpopup.XPopup
import com.starsea.book.base.VMBaseActivity
import com.starsea.book.databinding.AcitivitySignDetailsBinding
import com.starsea.book.ui.newpage.LoginActivity
import com.starsea.book.ui.newpage.adapter.SignDetailsCalAdapter
import com.starsea.book.ui.newpage.adapter.SignDetailsProgressAdapter
import com.starsea.book.ui.newpage.adapter.SignDetailsWeekAdapter
import com.starsea.book.ui.newpage.entity.Today
import com.starsea.book.ui.newpage.pop.SignHistoryPop
import com.starsea.book.ui.newpage.utils.Singleton
import com.starsea.book.ui.newpage.utils.finialDouble
import com.starsea.book.ui.newpage.viewmodel.WelfareViewModel
import com.starsea.book.utils.toastOnUi
import com.starsea.book.utils.viewbindingdelegate.viewBinding

/**
 * @author Lee
 * @createTime 2024-03-28 18 GMT+8
 * @desc :
 */
class SignDetailsActivity : VMBaseActivity<AcitivitySignDetailsBinding, WelfareViewModel>() {
    override val binding by viewBinding(AcitivitySignDetailsBinding::inflate)
    override val viewModel by viewModels<WelfareViewModel>()

    lateinit var mWeekAdapter: SignDetailsWeekAdapter
    lateinit var mProgressAdapter: SignDetailsProgressAdapter
    lateinit var mCalAdapter: SignDetailsCalAdapter

    @SuppressLint("SetTextI18n")
    override
    fun onActivityCreated(savedInstanceState: Bundle?) {

        mWeekAdapter = SignDetailsWeekAdapter(this)
//        binding.rvWeek.layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
        binding.rvWeek.layoutManager = GridLayoutManager(this, 7)
        binding.rvWeek.adapter = mWeekAdapter
        mWeekAdapter.setItems(viewModel.getWeek())


        viewModel.signList()


        viewModel.signListResult.observe(this) { data ->
            if (data.status == 200) {
                binding.tvSignDay.text = data.data!!.today!!.time ?: ""


                binding.tvSignHint.text = "再签1天，可获得${
                    (data.data!!.today!!.amount ?: "").toDouble().finialDouble()
                }金币奖励！"

                mProgressAdapter = SignDetailsProgressAdapter(this, data.data!!.today!!)
                binding.rvSignProgress.layoutManager =
                    LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
                binding.rvSignProgress.adapter = mProgressAdapter

                mProgressAdapter.setItems(data.data!!.welfareData)


                mCalAdapter = SignDetailsCalAdapter(this, data.data!!.today!!) {

                    XPopup.Builder(this@SignDetailsActivity)
                        .isDestroyOnDismiss(true)
                        .asCustom(
                            SignHistoryPop(
                                this@SignDetailsActivity,
                                it.date!!,
                                data.data!!.fillCheckAmount ?: "0"
                            ) { type ->
                                if (type == 0) {
                                    showAdaVideo(it.date ?: "", 1)
                                } else {
                                    viewModel.signHistory(it.date ?: "")
                                }
                            })
                        .show()
                }
                binding.rvSignDetails.layoutManager =
                    GridLayoutManager(this, 7)
                binding.rvSignDetails.adapter = mCalAdapter

                val dataFirst = data.data!!.welfareData!!.first()

                val week = Singleton.getWeekByDateInt(dataFirst.date ?: "")

                val fakeData: MutableList<Today> = arrayListOf()

                for (a in 1 until week) {
                    fakeData.add(Today())
                }

                fakeData.addAll(data.data!!.welfareData!!)

                mCalAdapter.setItems(fakeData)


            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(data.msg)
            }
        }


        viewModel.signHistoryResult.observe(this) { data ->
            if (data.status == 200) {
                toastOnUi("补签成功")
                viewModel.signList()
            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(data.msg)
            }
        }


    }

    private fun showAdaVideo(data: String, type: Int) {
        showLoading("广告加载中...")
        //创建TTAdNative对象，createAdNative(Context context) context需要传入Activity对象
        val mTTAdNative =
            TTAdSdk.getAdManager().createAdNative(this)

        val adSlot = AdSlot.Builder()
            .setCodeId("956204408")
            .setOrientation(TTAdConstant.VERTICAL)
            .setAdLoadType(TTAdLoadType.LOAD)
            .build()

        mTTAdNative.loadRewardVideoAd(adSlot,
            object : TTAdNative.RewardVideoAdListener {
                override fun onError(p0: Int, p1: String?) {
                    LogUtils.e(">>>> p0 = ${p0} \n p1 = ${p1}")
                }

                override fun onRewardVideoAdLoad(p0: TTRewardVideoAd?) {
                }

                override fun onRewardVideoCached() {
                }

                override fun onRewardVideoCached(ttRewardVideoAd: TTRewardVideoAd?) {
                    dismissLoading()
                    ttRewardVideoAd!!.showRewardVideoAd(this@SignDetailsActivity)

                    ttRewardVideoAd.setRewardAdInteractionListener(object :
                        TTRewardVideoAd.RewardAdInteractionListener {
                        override fun onAdShow() {
                            LogUtils.e(">>>> 广告展示")
                            // 广告展示
                        }

                        override fun onAdVideoBarClick() {
                            // 广告点击
                            LogUtils.e(">>>> 广告点击")
                        }

                        override fun onAdClose() {
                            // 广告关闭
                            LogUtils.e(">>>> 广告关闭")
                        }

                        override fun onVideoComplete() {
                            LogUtils.e(">>>> 广告素材播放完成，例如视频未跳过，完整的播放了")
                        }

                        override fun onVideoError() {
                            LogUtils.e(">>>> 广告展示时出错")
                        }

                        override fun onRewardVerify(
                            p0: Boolean,
                            p1: Int,
                            p2: String?,
                            p3: Int,
                            p4: String?
                        ) {
                        }

                        // 奖励发放
                        override fun onRewardArrived(
                            p0: Boolean,
                            p1: Int,
                            p2: Bundle?
                        ) {
                            toastOnUi("奖励已发放")

                            viewModel.adverReward(data, type)

                            LogUtils.e(">>>> 奖励发放")
                            LogUtils.e(">>>> p0 = ${p0} \n p1 = ${p1} \n ")
                        }

                        // // 用户在观看时点击了跳过
                        override fun onSkippedVideo() {
                            LogUtils.e(">>>> 用户在观看时点击了跳过")
                        }

                    })
                }
            })


    }
}